<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        width: 200px;
        height: 200px;
        border: 1px solid;
        background-color: cadetblue;
      }
      #box1 {
        width: 200px;
        height: 200px;
        border: 1px solid;
        background-color: cornflowerblue;
      }
    </style>
  </head>
  <body>
    <div id="box">节流盒子</div>
    <div id="box1">未节流盒子</div>
    <script>
      const Obox = document.getElementById("box");
      const Obox1 = document.getElementById("box1");
      function center(e) {
        console.log(1);
      }

      //绑定事件
      Obox.onmousemove = throttle(center, 300);

      Obox1.onmousemove = function () {
        console.log(1);
      };

      //封装一个节流函数
      function throttle(center, time) {
        //定义一个初始时间
        let lastTime = 0;
        //return后才是真正的事件函数
        return function (e) {
          let nowTime = Date.now();
          //如果上次的时间 减去现在的时间 小于并等于传入的time 则直接退出
          if (nowTime - lastTime <= time) return;
          lastTime = nowTime;
          center.call(this, e);
        };
      }
    </script>
  </body>
</html>
